<template>
  <el-dialog
    :visible.sync="dialogFormVisible"
    :title="title"
    width="40%"
    :before-close="handleclose"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="140px" show-message auto-complete="on">
      <el-form-item label="人员名称:" prop="userName">
        <el-input
          v-model.trim="form.userName"
          type="text"
          placeholder="请输入"
          maxlength="5"
          show-word-limit
          style="width:396px"
        />
      </el-form-item>
      <el-form-item label="角色:" prop="roleId">
        <el-select v-model="form.roleId" placeholder="请选择" style="width:396px">
          <el-option label="运营员" value="2" />
          <el-option label="维修员" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话:" prop="mobile">
        <el-input
          v-model="form.mobile"
          type="text"
          placeholder="请输入"
          maxlength="11"
          show-word-limit
          style="width:396px"
        />
      </el-form-item>
      <el-form-item label="负责区域:" prop="options">
        <el-select v-model="form.regionName" placeholder="请选择" style="width:396px" @change="getRegionID">
          <el-option
            v-for="item in form.options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="image">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <div class="img">
            <img v-if="form.image" :src="form.image" class="avatar" style="width:70px;height:70px">
            <i v-else class="el-icon-upload" />
          </div>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过100kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态:" prop="status">
        <el-checkbox v-model="form.status">是否启用</el-checkbox>
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="center">
      <el-button class="cancel" size="small" style="margin-right:34px" @click="cancel">取消</el-button>
      <el-button class="confirm" size="small" @click="confirm">确认</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { validphone } from '@/utils/validate'
import { imgUrlApi } from '@/api/common'
import { getAreaApi, getAreaIdApi } from '@/api/area'
import { addUserApi, editUserApi } from '@/api/user'
import { getUserSearchApi } from '@/api/user'

export default {
  props: {
    dialogFormVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '新增人员'
    }
  },
  data() {
    const phoneValid = (rules, value, callback) => {
      if (!validphone(value)) {
        callback(new Error('格式错误'))
      } else {
        callback()
      }
    }
    // 校验人员名称是否重复
    const mulUser = (rules, value, callback) => {
      console.log(value)
      const { data: { currentPageRecords }} = getUserSearchApi({ userName: value })
      console.log(currentPageRecords)
      if (currentPageRecords.role === value) {
        callback(new Error('该人员已存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        userName: '',
        roleId: '',
        mobile: '',
        options: {},
        regionName: '',
        regionId: '',
        image: '',
        status: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入', trigger: 'blur' },
          { pattern: mulUser, message: '该人员已存在', trigger: 'blur' }],
        roleId: [{ required: true }],
        mobile: [{ required: true, message: '手机号必填', trigger: 'blur' },
          { pattern: phoneValid, tirgger: 'blur', message: '手机号格式不对' }
        ],
        regionName: [{ required: true, message: '请输入', trigger: 'blur' }],
        image: [{ required: true, message: '请上传', trigger: 'blur' }]

      },
      page: {
        // 放置页码及相关数据
        pageIndex: 1,
        pageSize: 10000
      },
      loading: false
    }
  },
  created() {
    this.getArea()
  },
  methods: {
    async  handleAvatarSuccess(res, file) {
      // 返回图片地址
      const { data } = await imgUrlApi(file.raw)
      console.log(data)
      this.form.image = data
    },
    // 图片校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt200KB = file.size / 1024 < 200

      if (!isJPG || !isPNG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt200KB) {
        this.$message.error('上传头像图片大小不能超过 200kb!')
      }
      return isJPG || isPNG && isLt200KB
    },
    // 获取负责区域
    async getArea() {
      try {
        const { data: { currentPageRecords }} = await getAreaApi(this.page)
        // console.log(currentPageRecords)
        this.form.options = currentPageRecords
      // this.options.regionName = currentPageRecords.name
      // this.options.regionId = currentPageRecords.id
      } catch (error) {
        console.log(error)
      }
    },
    handleclose() {
      this.$parent.dialogFormVisible = false
      this.$refs.form.resetFields()
    },
    // 点击取消重置表单
    cancel() {
      this.$refs.form.resetFields()
      this.$parent.dialogFormVisible = false
      // console.log(this.$parent)
    },
    async getRegionID() {
      try {
        const { data: { id, name }} = await getAreaIdApi(this.form.regionName)
        // console.log(data)
        this.form.regionId = id
        this.form.regionName = name
      } catch (error) {
        console.log(error)
      }
    },
    // 确认提交
    async confirm() {
      try {
        await this.$refs.form.validate()
        this.loading = true
        console.log(this.form.id)
        this.form.id ? await editUserApi(this.form.id, this.form) : await addUserApi(this.form)
        this.$parent.dialogFormVisible = false
        // 提交完之后重置表单
        this.$refs.form.resetFields()
        // 重新渲染列表
        this.$parent.getRoleList()
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    }

  }

}
</script>

<style lang="scss">
.el-dialog {
  border-radius:10px;
}
.el-dialog__body {
  padding: 20px 20px 30px;
}
.img {
      // position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
    overflow: hidden;
    background: #f3f6fb;
    width: 84px;
    height: 84px;
    border: 1px dashed #d8dde3;
    border-radius: 4px;
    cursor: pointer;
}
</style>
